package ru.artyushov.fingers.ui;

import ru.artyushov.fingers.ui.callbacks.ImageSelectionListener;
import ru.artyushov.fingers.ui.callbacks.ImageViewedListener;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;

public class UiMainWindow {

    private JFrame window = null;

    public void startAndShowFileChooser(ImageSelectionListener callback) {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.showOpenDialog(null);
        File file = fileChooser.getSelectedFile();
        callback.onImageSelected(file.getAbsolutePath());
    }

    public void showImage(final BufferedImage image, String title, final ImageViewedListener listener) {
        int x = 0, y = 0;
        if (window != null) {
            x = window.getX();
            y = window.getY();
            window.dispose();
        }
        window = new JFrame(title);
        window.setLocation(x, y);
        window.setLayout(new BoxLayout(window.getContentPane(), BoxLayout.Y_AXIS));
        window.setSize(image.getWidth(), image.getHeight() + 100);
        JLabel imageLabel = new JLabel(new ImageIcon(image));
        window.add(imageLabel);
        JButton button = new JButton("Next");
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                listener.onImageViewed(image);
            }
        });
        window.add(button);
        window.repaint();
        window.setVisible(true);
    }

    public void stop() {
        if (window != null) {
            window.dispose();
        }
    }
}
